package hn.cch.spring.aop;

import hn.cch.spring.aop.aspect.AopConfiguration1;
import hn.cch.spring.aop.aspect.ExecutionAspect;
import hn.cch.spring.aop.aspect.ExecutionTarget0;
import hn.cch.spring.aop.aspect.ExecutionTarget1;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.Advisor;
import org.springframework.context.annotation.ConfigurationClassPostProcessor;
import org.springframework.context.support.GenericApplicationContext;

import java.util.List;

public class AutoProxyCreatorDemo {

    private static final Logger logger = LoggerFactory.getLogger(AutoProxyCreatorDemo.class);

    public static void main(String[] args) {
        // 代理创建流程
        GenericApplicationContext applicationContext = new GenericApplicationContext();
        applicationContext.registerBean(ConfigurationClassPostProcessor.class);
        applicationContext.registerBean(AopConfiguration1.class);
        applicationContext.registerBean(ExecutionAspect.class);
        applicationContext.refresh();


        // applicationContext.registerBean(AnnotationAwareAspectJAutoProxyCreator.class);
        applicationContext.registerBean(MyAutoProxyCreator.class);

        // AnnotationAwareAspectJAutoProxyCreator creator = applicationContext.getBean(AnnotationAwareAspectJAutoProxyCreator.class);
        MyAutoProxyCreator creator = applicationContext.getBean(MyAutoProxyCreator.class);
        // 获取符合条件的Advisor
        List<Advisor> advisorList = creator.findEligibleAdvisors(ExecutionTarget0.class, "executionProxy0");
        // List<Advisor> advisorList = creator.findEligibleAdvisors(ExecutionProxy1.class, "executionProxy1");
        advisorList.forEach(System.out::println);

        // findEligibleAdvisors返回集合非空就需要创建代理
        Object object0 = creator.wrapIfNecessary(new ExecutionTarget0(), "executionProxy0", "executionProxy0");
        logger.debug(object0.getClass().toString());
        ExecutionTarget0 executionTarget0 = (ExecutionTarget0) object0;
        String around = executionTarget0.around("xyz");
        Object object1 = creator.wrapIfNecessary(new ExecutionTarget1(), "executionProxy1", "executionProxy1");
        logger.debug(object1.getClass().toString());

        applicationContext.close();

    }

}
